package com.aiyige.page.publish.selectvideocover;

import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.utils.ImageCropper;
import com.aiyige.utils.VideoUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.dialog.LoadingDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.yalantis.ucrop.UCrop;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Route(path = ARouterConfig.SelectVideoCoverPage)
public class SelectVideoCoverPage extends AppCompatActivity {
    public static final String EXTRA_KEY_VIDEO_COVER_URL = "com.aiyige.extra.EXTRA_KEY_VIDEO_COVER_URL";
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.titleActionBtn)
    Button titleActionBtn;
    @BindView(R.id.videoView)
    VideoView videoView;
    @BindView(R.id.seekBar)
    SeekBar seekBar;

    @Autowired
    String videoUrl;
    Handler mainHandler;
    String originalPath = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_select_video_cover);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        titleTv.setText(R.string.select_cover);
        titleActionBtn.setText(R.string.next);
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                seekBar.setMax(mp.getDuration());
                mp.seekTo(0);
                mp.setVolume(0, 0);
                mp.start();
                mp.pause();
            }
        });
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                videoView.seekTo(progress);
                videoView.start();
                videoView.pause();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        mainHandler = new Handler(Looper.getMainLooper());
        mainHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                videoView.setVisibility(View.VISIBLE);
                videoView.setVideoPath(videoUrl);
            }
        }, 1000);

    }

    @OnClick({R.id.titleBackBtn, R.id.titleActionBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn: {
                setResult(RESULT_CANCELED);
                finish();
                break;
            }
            case R.id.titleActionBtn: {
                new AsyncTask<Long, Object, String>() {
                    LoadingDialog loadingDialog;

                    @Override
                    protected void onPreExecute() {
                        loadingDialog = LoadingDialog.newBuilder()
                                .with(SelectVideoCoverPage.this)
                                .message(R.string.text_process)
                                .show();
                    }

                    @Override
                    protected String doInBackground(Long... params) {
                        return VideoUtil.getVideoCover(videoUrl, params[0]);
                    }

                    @Override
                    protected void onPostExecute(String s) {
                        loadingDialog.dismiss();
                        if (TextUtils.isEmpty(s)) {
                            ToastX.show(R.string.select_cover_failed);
                        } else {
                            originalPath = s;
                            startCrop(originalPath);
                        }
                    }
                }.execute((long) (videoView.getCurrentPosition()));
                break;
            }
        }
    }

    public void startCrop(String path) {
        ImageCropper.newBuilder()
                .activity(this)
                .path(path)
                .aspectRatioX(16)
                .aspectRatioY(9)
                .build()
                .startCrop();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case UCrop.REQUEST_CROP:
                if (resultCode == RESULT_OK) {
                    try {
                        Uri resultUri = UCrop.getOutput(data);
                        String cutPath = resultUri.getPath();
                        doSelectCover(cutPath);
                    } catch (Exception e) {
                        doSelectCover(originalPath);
                    }
                }
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }

    }

    public void doSelectCover(String path) {
        Intent intent = new Intent();
        intent.putExtra(EXTRA_KEY_VIDEO_COVER_URL, path);
        setResult(RESULT_OK, intent);
        finish();
    }
}
